﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using Resources;
using Wicresoft.RDW.Presentation;
using Wicresoft.RDW.Utility;

namespace Wicresoft.RDW.UserControls
{
    public partial class RequestBasicControl : UserControl
    {
        public delegate void LoadUserControl(int typeId, int labId);
        public event LoadUserControl RequestTypeChanged;

        protected BasePage BasePage
        {
            get
            {
                return this.Page as BasePage;
            }
        }
        public Model.Request RequestData
        {
            get
            {
                int startHour = Convert.ToInt32(ddlStartHour.SelectedValue);
                int startMinute = Convert.ToInt32(ddlStartMinute.SelectedValue);
                int endHour = Convert.ToInt32(ddlEndHour.SelectedValue);
                int endMinute = Convert.ToInt32(ddlEndMinute.SelectedValue);
                Model.Request data = new Model.Request()
                {
                    RequestId = BasePage.Id,
                    LabId = string.IsNullOrEmpty(txtLab.Text) ? 0 : Convert.ToInt32(txtLab.Text),
                    StartTime = new TimeSpan(startHour, startMinute, 0),
                    EndTime = new TimeSpan(endHour, endMinute, 0),
                    RequestType = string.IsNullOrEmpty(ddlRequestType.SelectedValue) ? 0 : Convert.ToInt32(ddlRequestType.SelectedValue),
                    Status = (int)RequestStatus.Draft,
                    RequestUserId = BasePage.CurrentUserId,
                    CreateTime = DateTime.Now,
                    Comments = txtComments.Text.Trim() == "" ? "" : string.Format("{0}:<br/>{1}", BasePage.CurrentUserName, txtComments.Text.Trim())
                };
                if (string.IsNullOrEmpty(txtApplyDate.Text))
                {
                    data.RequestDate = DateTime.Today;
                }
                else
                {
                    data.RequestDate = Convert.ToDateTime(txtApplyDate.Text);
                }
                return data;
            }
        }
        public bool ValidateForm
        {
            get
            {
                rfvLocation.Validate();
                rfvLab.Validate();
                rfvRequestType.Validate();
                this.cvApplyDateServerValidate();

                if (rfvLocation.IsValid && rfvLab.IsValid && rfvRequestType.IsValid && cvApplyDate.IsValid)
                    return true;
                else
                    return false;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (BasePage.PageStatus == PageStatus.Readonly)
                {
                    Wicresoft.RDW.Utility.Helper.ControlEditable(this, false);
                }
                else
                {
                    Wicresoft.RDW.Utility.Helper.ControlEditable(this, true);
                    if (BasePage.PageStatus == PageStatus.Edit)
                    {
                        ddlRequestType.Attributes.Add("disabled", "disabled");
                    }
                }
                InitResource();
                InitControl();
                LoadData();
            }
        }
        public void InitResource()
        {
            rfvLocation.ErrorMessage = NameResource.Location_Name + CommonResource.NotNull;
            rfvLab.ErrorMessage = NameResource.Lab_Name + CommonResource.NotNull;
            rfvRequestType.ErrorMessage = NameResource.Request_RequestType + CommonResource.NotNull;
            rfvApplyDate.ErrorMessage = NameResource.Visit_Date + CommonResource.NotNull;
            revApplyDate.ErrorMessage = NameResource.Visit_Date + CommonResource.ErrorFormat;
            this.txtCommentsValidator.ErrorMessage = string.Format(Resources.NameResource.OverMaxLength, 100);
        }
        protected void InitControl()
        {
            ddlLocation.DataValueField = "LocationId";
            ddlLocation.DataTextField = BasePage.Language == Utility.Language.CN ? "Name_CN" : "Name_EN";
            ddlLocation.DataSource = LocationPresent.GetList();
            ddlLocation.DataBind();

            ddlLocation.Items.Insert(0, new ListItem(CommonResource.PleaseSelect, ""));

            if (BasePage.PageStatus == PageStatus.Edit)
            {
                ddlLab.DataValueField = "LabId";
                ddlLab.DataTextField = "Name";
                ddlLab.DataSource = LabPresent.GetList();
                ddlLab.DataBind();
            }
            ddlLab.Items.Insert(0, new ListItem(CommonResource.PleaseSelect, ""));

            ddlRequestType.Items.Add(new ListItem(CommonResource.PleaseSelect, ""));
            ddlRequestType.Items.Add(new ListItem(NameResource.RequestType_Visit, ((int)RequestType.Visit).ToString()));
            ddlRequestType.Items.Add(new ListItem(NameResource.RequestType_SiteBorrow, ((int)RequestType.SiteBorrow).ToString()));
            ddlRequestType.Items.Add(new ListItem(NameResource.RequestType_Testing, ((int)RequestType.Testing).ToString()));

            for (int i = 9; i < 18; i++)
            {
                ddlStartHour.Items.Add(i.ToString());
                ddlEndHour.Items.Add(i.ToString());
            }
            LoadMinute(ddlStartMinute);
            LoadMinute(ddlEndMinute);

        }
        protected void LoadMinute(DropDownList ddl)
        {
            ddl.Items.Add("00");
            ddl.Items.Add("15");
            ddl.Items.Add("30");
            ddl.Items.Add("45");
        }
        protected void LoadData()
        {
            if (BasePage.PageStatus == PageStatus.New)
                return;

            Model.Request request = RequestPresent.GetById(BasePage.Id);
            ddlLocation.SelectedValue = request.Lab.LocationId.ToString();
            txtLab.Text = request.LabId.ToString();
            if (request.Status == (int)RequestStatus.Draft && request.RequestDate < DateTime.Today)
            {
                txtApplyDate.Text = "";
            }
            else
            {
                txtApplyDate.Text = request.RequestDate.ToString("yyyy-MM-dd");
            }
            ddlRequestType.SelectedValue = request.RequestType.ToString();
            ddlStartHour.SelectedValue = request.StartTime.Hours.ToString();
            ddlStartMinute.SelectedValue = request.StartTime.Minutes.ToString("##");
            ddlEndHour.SelectedValue = request.EndTime.Hours.ToString();
            ddlEndMinute.SelectedValue = request.EndTime.Minutes.ToString("##");
            txtComments.Visible = false;
            if (!string.IsNullOrEmpty(request.Comments))
            {
                phComments.Visible = true;
                litComments.Text = Server.HtmlDecode(request.Comments);
                if (request.Status == (int)RequestStatus.AskForMore && BasePage.IsCurrentApplyUser)
                {
                    if (!string.Equals(BasePage.GetQueryString("pageStatus"), PageStatus.Readonly.ToString(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        txtComments.Visible = true;
                        comment_UserControl.Enabled = true;
                        comment_UserControl.ErrorMessage = Resources.NameResource.Comments + Resources.CommonResource.NotNull;
                    }
                }
            }
            else
            {
                phComments.Visible = false;
            }
            RequestTypeChanged(request.RequestType, request.LabId);
        }

        protected void ddlRequestType_SelectedIndexChanged(object sender, EventArgs e)
        {
            string labId = txtLab.Text.Trim();
            if (string.IsNullOrEmpty(labId))
            {
                ddlRequestType.SelectedValue = "";
                cvRequestType.IsValid = false;
                cvRequestType.ErrorMessage = NameResource.cvRequestType;
                RequestTypeChanged(0, 0);
                return;
            }
            var typeId = string.IsNullOrEmpty(ddlRequestType.SelectedValue) ? 0 : Convert.ToInt32(ddlRequestType.SelectedValue);
            RequestTypeChanged(typeId, Convert.ToInt32(labId));
            this.cvApplyDateServerValidate();
        }

        private void cvApplyDateServerValidate()
        {
           
            int startHour = Convert.ToInt32(ddlStartHour.SelectedValue);
            int startMinute = Convert.ToInt32(ddlStartMinute.SelectedValue);
            int endHour = Convert.ToInt32(ddlEndHour.SelectedValue);
            int endMinute = Convert.ToInt32(ddlEndMinute.SelectedValue);
            var startTime = new TimeSpan(startHour, startMinute, 0);
            var endTime = new TimeSpan(endHour, endMinute, 0);
            var nineOclock = new TimeSpan(9, 0, 0);
            var applyDate = DateTime.Today;
            DateTime.TryParse(txtApplyDate.Text, out applyDate);
            if(applyDate==new DateTime()&&!string.IsNullOrEmpty(txtApplyDate.Text)){
                revApplyDate.IsValid = false;
                return;
            }
            int labId = string.IsNullOrEmpty(txtLab.Text) ? 0 : Convert.ToInt32(txtLab.Text);
            var labCloseSchedule = LabCloseSchedulePresent.GetList(p => p.LabId == labId);
            //验证关闭的实验室不能申请
            if (!string.IsNullOrEmpty(txtApplyDate.Text))
            {
                for (int i = 0; i < labCloseSchedule.Count; i++)
                {
                    if (applyDate >= labCloseSchedule[i].StartDate && applyDate <= labCloseSchedule[i].EndDate)
                    {
                        cvApplyDate.IsValid = false;
                        cvApplyDate.ErrorMessage = NameResource.LabClose_Validation;
                        return;
                    }
                }

                var applyStartTime = applyDate.Add(startTime);
                //验证申请日期必须提前24小时
                if (applyStartTime > DateTime.Now.AddHours(double.Parse(SysSettingPresent.ApplyBeforeHour)))
                {
                    var time = new TimeSpan(0, 30, 0);
                    if (startTime != nineOclock || endTime != nineOclock)
                    {
                        //验证结束时间要晚于开始时间30分钟
                        if (endTime < startTime.Add(time))
                        {
                            cvApplyDate.IsValid = false;
                            cvApplyDate.ErrorMessage = NameResource.Time_Validation;
                            return;
                        }
                    }
                }
                else
                {
                    cvApplyDate.IsValid = false;
                    cvApplyDate.ErrorMessage = string.Format(NameResource.ApplyDate_Validation, SysSettingPresent.ApplyBeforeHour);
                    return;
                }
                if (startTime != nineOclock || endTime != nineOclock)
                {
                    var applyEndTime = applyDate.Add(endTime);
                    var request = RequestPresent.GetList(p => p.LabId == labId && (p.Status == (int)RequestStatus.Approved || p.Status == (int)RequestStatus.AskForMore || p.Status == (int)RequestStatus.Pending));
                    //验证对同一实验室的申请要间隔一段时间
                    for (int j = 0; j < request.Count; j++)
                    {
                        var requestEndDate = request[j].RequestDate.Add(request[j].EndTime).AddMinutes(double.Parse(SysSettingPresent.ApplyPeriodMinute));
                        var requestStartDate = request[j].RequestDate.Add(request[j].StartTime).AddMinutes(-double.Parse(SysSettingPresent.ApplyPeriodMinute));
                        //if ((applyStartTime < requestEndDate && applyStartTime > requestStartDate) || (applyEndTime > requestStartDate && applyEndTime < requestEndDate)
                        //    || (applyEndTime <= requestEndDate && applyStartTime >= requestStartDate) || (applyEndTime > requestEndDate && applyStartTime < requestStartDate))
                        if (applyStartTime >= requestEndDate || applyEndTime <= requestStartDate)
                        { continue; }
                        else
                        {
                            cvApplyDate.IsValid = false;
                            cvApplyDate.ErrorMessage = string.Format(NameResource.LabVisit_Validation, SysSettingPresent.ApplyPeriodMinute);
                            return;
                        }
                    }
                }
            }
            cvApplyDate.IsValid = true;
        }

        protected void txtApplyDate_TextChanged(object sender, EventArgs e)
        {
            string strFunName = Request.Form["FunName"] != null ? Request.Form["FunName"] : "";
            switch (strFunName)
            {
                case "cvApplyDateServerValidate":
                    cvApplyDateServerValidate();
                    break;
                case "":
                    break;
            }
        }

        protected void cvApplyDate_ServerValidate(object source, ServerValidateEventArgs args)
        {
            int startHour = Convert.ToInt32(ddlStartHour.SelectedValue);
            int startMinute = Convert.ToInt32(ddlStartMinute.SelectedValue);
            int endHour = Convert.ToInt32(ddlEndHour.SelectedValue);
            int endMinute = Convert.ToInt32(ddlEndMinute.SelectedValue);
            var startTime = new TimeSpan(startHour, startMinute, 0);
            var endTime = new TimeSpan(endHour, endMinute, 0);

            var applyDate = DateTime.Today;
            DateTime.TryParse(txtApplyDate.Text, out applyDate);
            if (applyDate == new DateTime() && !string.IsNullOrEmpty(txtApplyDate.Text))
            {
                revApplyDate.IsValid = false;
                return;
            }
            int labId = string.IsNullOrEmpty(txtLab.Text) ? 0 : Convert.ToInt32(txtLab.Text);
            var labCloseSchedule = LabCloseSchedulePresent.GetList(p => p.LabId == labId);
            //验证关闭的实验室不能申请
            for (int i = 0; i < labCloseSchedule.Count; i++)
            {
                if (applyDate >= labCloseSchedule[i].StartDate && applyDate <= labCloseSchedule[i].EndDate)
                {
                    args.IsValid = false;
                    cvApplyDate.ErrorMessage = NameResource.LabClose_Validation;
                    return;
                }
            }

            var applyStartTime = applyDate.Add(startTime);
            //验证申请日期必须提前24小时
            if (applyStartTime > DateTime.Now.AddHours(double.Parse(SysSettingPresent.ApplyBeforeHour)))
            {
                var time = new TimeSpan(0, 30, 0);
                //验证结束时间要晚于开始时间30分钟
                if (endTime < startTime.Add(time))
                {
                    args.IsValid = false;
                    cvApplyDate.ErrorMessage = NameResource.Time_Validation;
                    return;
                }
            }
            else
            {
                args.IsValid = false;
                cvApplyDate.ErrorMessage = string.Format(NameResource.ApplyDate_Validation, SysSettingPresent.ApplyBeforeHour);
                return;
            }

            var applyEndTime = applyDate.Add(endTime);
            var request = RequestPresent.GetList(p => p.LabId == labId && (p.Status == (int)RequestStatus.Approved || p.Status == (int)RequestStatus.AskForMore || p.Status == (int)RequestStatus.Pending));
            //验证对同一实验室的申请要间隔一段时间
            for (int j = 0; j < request.Count; j++)
            {
                var requestEndDate = request[j].RequestDate.Add(request[j].EndTime).AddMinutes(double.Parse(SysSettingPresent.ApplyPeriodMinute));
                var requestStartDate = request[j].RequestDate.Add(request[j].StartTime).AddMinutes(-double.Parse(SysSettingPresent.ApplyPeriodMinute));
                //if ((applyStartTime < requestEndDate && applyStartTime > requestStartDate) || (applyEndTime > requestStartDate && applyEndTime < requestEndDate)
                //    || (applyEndTime <= requestEndDate && applyStartTime >= requestStartDate) || (applyEndTime > requestEndDate && applyStartTime < requestStartDate))
                if (applyStartTime >= requestEndDate || applyEndTime <= requestStartDate)
                { continue; }
                else
                {
                    args.IsValid = false;
                    cvApplyDate.ErrorMessage = string.Format(NameResource.LabVisit_Validation, SysSettingPresent.ApplyPeriodMinute); ;
                    return;
                }
            }
            args.IsValid = true;
        }

    }
}